<?php 
/**
 * 优惠卷程序
 * 编写人    陈泽富
*/

define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
// /* act操作项的初始化 */
if (empty($_REQUEST['act']))
{
    $act = 'list';
}
else
{
    $act = trim($_REQUEST['act']);
}
/*添加优惠卷*/
if ($act == 'add') {
    $smarty->assign('ur_here',         "添加优惠卷");
    $smarty->assign('full_page',        1);
    $smarty->assign('type_list', type_list());
    $smarty->assign('action_link',      array('text' => '优惠卷列表', 'href' => 'coupon.php?act=list'));
    $smarty->display('coupon/coupon_add.htm');
}
/*处理提交数据*/
if ($act == 'post') { 

    $type_id = !empty($_REQUEST['type_id'])?intval($_REQUEST['type_id']):'0';
    $coupon_name   = !empty($_REQUEST['coupon_name'])?$_REQUEST['coupon_name']:'0';
    $use_price   = !empty($_REQUEST['use_price'])?$_REQUEST['use_price']:'0';
    $out_number  = !empty($_REQUEST['out_number'])?$_REQUEST['out_number']:'1';
    $start_time  = !empty($_REQUEST['start_time'])?strtotime($_REQUEST['start_time']):'0';
    $end_time    = !empty($_REQUEST['end_time'])?strtotime($_REQUEST['end_time']):'0';
    $get_start_time  = !empty($_REQUEST['get_start_time'])?strtotime($_REQUEST['get_start_time']):'0';
    $get_end_time    = !empty($_REQUEST['get_end_time'])?strtotime($_REQUEST['get_end_time']):'0';

    $add_time = time();
    $coupon_code = coupon_code();//获取优惠卷批次标识
    $sql =  " INSERT INTO ".$ecs->table('coupon')."( type_id,coupon_name, use_price, start_time, end_time,get_start_time,get_end_time, add_time,coupon_code) VALUES ".
            " ($type_id,'$coupon_name',$use_price,$start_time,$end_time,$get_start_time,$get_end_time,$add_time,'$coupon_code')";
    for ($number=1; $number < $out_number; $number++) {
        $sql =$sql ." , ($type_id,'$coupon_name',$use_price,$start_time,$end_time,$get_start_time,$get_end_time,$add_time,'$coupon_code')";
    }
    if ($db->query($sql)) {
        $links[] = array('href' => 'coupon.php?act=list', 'text' => "添加优惠卷成功");
        sys_msg("发放优惠卷成功", 100, $links);
    }

}
/*优惠卷列表*/
if ($act == 'list') {
    $smarty->assign('ur_here',          $_LANG['13_coupon_list']);
    $coupon_list = coupon_list();
    $smarty->assign('full_page',        1);
    $smarty->assign('coupon_list',  $coupon_list['coupon_list']);
    $smarty->assign('filter',       $coupon_list['filter']);
    $smarty->assign('record_count', $coupon_list['record_count']);
    $smarty->assign('page_count',   $coupon_list['page_count']);
    $smarty->assign('action_link',      array('text' => '添加优惠卷', 'href' => 'coupon.php?act=add'));
    $smarty->display('coupon/coupon_list.htm');
}
/*优惠卷翻页*/
if ($act == 'query') {
    $coupon_list = coupon_list();
    $smarty->assign('coupon_list',  $coupon_list['coupon_list']);
    $smarty->assign('filter',       $coupon_list['filter']);
    $smarty->assign('record_count', $coupon_list['record_count']);
    $smarty->assign('page_count',   $coupon_list['page_count']);
    make_json_result($smarty->fetch('coupon/coupon_list.htm'), '', array('filter' => $coupon_list['filter'], 'page_count' => $coupon_list['page_count']));
}


/*优惠卷详情*/
if ($act == 'info') {
    $coupon_info = coupon_info();
    $smarty->assign('coupon_info',  $coupon_info['coupon_info']);
    $smarty->assign('filter',       $coupon_info['filter']);
    $smarty->assign('record_count', $coupon_info['record_count']);
    $smarty->assign('page_count',   $coupon_info['page_count']);
    $smarty->assign('full_page',        1);
    $smarty->assign('action_link',      array('text' => '优惠卷列表', 'href' => 'coupon.php?act=list'));
    $smarty->display('coupon/coupon_info.htm');
}

/*优惠卷翻页*/
if ($act == 'info_query') {
    $coupon_info = coupon_info();
    $smarty->assign('coupon_info',  $coupon_info['coupon_info']);
    $smarty->assign('filter',       $coupon_info['filter']);
    $smarty->assign('record_count', $coupon_info['record_count']);
    $smarty->assign('page_count',   $coupon_info['page_count']);
    make_json_result($smarty->fetch('coupon/coupon_info.htm'), '', array('filter' => $coupon_info['filter'], 'page_count' => $coupon_info['page_count']));
}









/*删除优惠卷*/
if ($act == 'delete') {
    $coupon_code = $_REQUEST['id'];
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $return = array('error' => '0','message' =>'成功' );
    /*查看能否整批删除优惠卷*/
    $sql = "SELECT count(*) FROM ".$ecs->table('coupon')."WHERE is_exchange = 1 ";
    $is_delete = $db->getOne($sql);
    if (!empty($is_delete)) {
        $return = array('error' => '4','message' =>'优惠卷已被兑换无法删除' );
        echo $json->encode($return);
        exit();
    }
    $sql = "DELETE FROM ".$ecs->table('coupon')."WHERE coupon_code = '$coupon_code'";
    $db->query($sql);
    echo $json->encode($return);
    exit();
}
/*删除优惠卷(单个)*/
if ($act == 'remove') {
    $coupon_id = $_REQUEST['id'];
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $return = array('error' => '0','message' =>'成功' );
    /*查看能否整批删除优惠卷*/
    $sql = "SELECT count(*) FROM ".$ecs->table('coupon')."WHERE is_exchange = 1 AND coupon_id = $coupon_id";
    $is_delete = $db->getOne($sql);
    if (!empty($is_delete)) {
        $return = array('error' => '4','message' =>'优惠卷已被兑换无法删除' );
        echo $json->encode($return);
        exit();
    }
    $sql = "DELETE FROM ".$ecs->table('coupon')."WHERE coupon_id = '$coupon_id'";
    $db->query($sql);
    echo $json->encode($return);
    exit();
}



/*修改发放数量*/
if ($act == 'edit_out_number') {
    $out_number  = $_REQUEST['val'];
    $coupon_code = $_REQUEST['id'];
    require(ROOT_PATH . 'includes/cls_json.php');
    $json   = new JSON;
    $return = array('error' => '0','message' =>'','content'=> $out_number);
    /*查询当前发放数量*/
    $sql ="SELECT count(*) FROM ".$ecs->table('coupon')."WHERE coupon_code = '$coupon_code'";
    $out_number_now = $db->getOne($sql);

    if ($out_number_now === $out_number) {
    echo $json->encode($return);
    exit();
    }

    if ($out_number_now<$out_number) {
      $time = time();
      $num = intval($out_number - $out_number_now);
      $sql = 'SELECT * FROM '.$ecs->table('coupon')."WHERE coupon_code = '$coupon_code'";
      $coupon_info =$db->getRow($sql);
      $sql =  " INSERT INTO ".$ecs->table('coupon').
              " (coupon_code,type_id,coupon_name, use_price, start_time, end_time, add_time) VALUES ".
              " ('$coupon_code','$coupon_info[type_id]','$coupon_info[coupon_name]','$coupon_info[use_price]','$coupon_info[start_time]','$coupon_info[end_time]','$time')";
    for ($number=1; $number < $num; $number++) {
        $sql =$sql ." , ('$coupon_code','$coupon_info[type_id]','$coupon_info[coupon_name]','$coupon_info[use_price]','$coupon_info[start_time]','$coupon_info[end_time]','$time')";
    }
    $db->query($sql);
    $return = array('error' => '0','message' =>'发放成功','content'=> $out_number);
    echo $json->encode($return);
    exit();

    }




}





function type_list(){
    $sql ="SELECT * FROM ".$GLOBALS['ecs']->table('coupon_type');
    $type =$GLOBALS['db']->getAll($sql);


    return $type;
}

function coupon_code(){
    $str = null;
    $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
    $max = strlen($strPol)-1;

    for($i=0;$i<8;$i++){
    $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
    }

    $sql = " SELECT count(*) FROM ".$GLOBALS['ecs']->table('coupon').
      " WHERE coupon_code = '$str'";
    if ($GLOBALS['db']->getOne($sql)) {
      coupon_code();
    }
    else{
        return $str;
    }

}
function coupon_list(){
        
        $filter['order_sn'] = !empty($_REQUEST['order_sn']) ?$_REQUEST['order_sn'] :'';
        $filter['service_state'] = !empty($_REQUEST['service_state']) ?$_REQUEST['service_state'] :'';
        $filter['service_type'] = !empty($_REQUEST['service_type']) ?$_REQUEST['service_type'] :'';
        $filter['handle_state'] = !empty($_REQUEST['handle_state']) ?$_REQUEST['handle_state'] :'';
        $where = 'WHERE 1 ';
        if(!empty($filter['order_sn'])){
            $where .= ' AND s.order_sn = '.$filter['order_sn'];
        }

        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }


        $sql=   " SELECT c.* ,ct.type_name, count(c.coupon_code) AS out_number,sum(c.is_exchange) AS get_number,sum(c.is_use) AS use_number FROM ".
                $GLOBALS['ecs']->table('coupon')." AS c ".
                "LEFT JOIN ".$GLOBALS['ecs']->table('coupon_type')." AS ct ON c.type_id = ct.type_id ".
                $where." GROUP BY coupon_code ORDER BY add_time DESC";
        $filter['record_count'] = $GLOBALS['db']->num_rows($GLOBALS['db']->query($sql)); // 总数
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;//总数
        $sql = $sql." LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";
        $row = $GLOBALS['db']->getAll($sql);
        foreach ($row as $key => $value) {
            $row[$key]['add_time'] =date('Y-m-d-H:i:s',$value['add_time']);
            $row[$key]['start_time'] =date('Y-m-d-H:i:s',$value['start_time']);
            $row[$key]['end_time'] =date('Y-m-d-H:i:s',$value['end_time']);
            $row[$key]['get_start_time'] =date('Y-m-d-H:i:s',$value['get_start_time']);
            $row[$key]['get_end_time'] =date('Y-m-d-H:i:s',$value['get_end_time']);
        }
        $arr = array('coupon_list' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
        return $arr;
}

function coupon_info(){
        $filter['coupon_code'] = !empty($_REQUEST['coupon_code']) ?$_REQUEST['coupon_code'] :'';
        $where = 'WHERE 1 ';
        if(!empty($filter['coupon_code'])){
            $where .= " AND c.coupon_code = '".$filter['coupon_code']."'";
        }

        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }
        $sql =  " SELECT c.* ,u.user_name,ct.type_name FROM ".
                $GLOBALS['ecs']->table('coupon')." AS c ".
                " LEFT JOIN ".$GLOBALS['ecs']->table('users')." AS u  ON c.user_id = u.user_id ".
                " LEFT JOIN ".$GLOBALS['ecs']->table('coupon_type')." AS ct ON c.type_id = ct.type_id ".
                $where." ORDER BY coupon_id DESC";

        $filter['record_count'] = $GLOBALS['db']->num_rows($GLOBALS['db']->query($sql)); // 总数
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;//总数
        $sql = $sql." LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";

        
        $row = $GLOBALS['db']->getAll($sql);
        foreach ($row as $key => $value) {
            $row[$key]['add_time'] =date('Y-m-d-H:i:s',$value['add_time']);
            $row[$key]['start_time'] =date('Y-m-d-H:i:s',$value['start_time']);
            $row[$key]['end_time'] =date('Y-m-d-H:i:s',$value['end_time']);
            $row[$key]['exchange_time'] =!empty($value['exchange_time'])?date('Y-m-d-H:i:s',$value['exchange_time']):'0';
            $row[$key]['user'] =!empty($value['user_name'])?$value['user_name']:'未被领取';
        }
        $arr = array('coupon_info' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
        return $arr;


}

 ?>